package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;

import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private AnnouncementApi announcementApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private CommentApi commentApi;

    /**
     * 根据环信id查询用户详情
     */
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        //1、根据环信id查询用户
        User user = userApi.findByHuanxin(huanxinId);
        //2、根据用户id查询用户详情
        UserInfo userInfo = userInfoApi.findById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //添加好友关系
    public void contacts(Long friendId) {
        //1、将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + friendId);
        if(!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
        //2、如果注册成功，记录好友关系到mongodb
        friendApi.save(UserHolder.getUserId(),friendId);
    }

    //分页查询联系人列表
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //1、调用API查询当前用户的好友数据 -- List<Friend>
        List<Friend> list = friendApi.findByUserId(UserHolder.getUserId(),page,pagesize);
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //2、提取数据列表中的好友id
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //3、调用UserInfoAPI查询好友的用户详情
        UserInfo info = new UserInfo();
        info.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
        //4、构造VO对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if(userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0l,vos);
    }


    //公告列表
    public PageResult findannouncements(Integer page, Integer pagesize) {
        Page<Announcement> ipage = announcementApi.findannouncements(page,pagesize);
        return new PageResult(page,pagesize, ipage.getTotal(), ipage.getRecords());
    }


    //喜欢/点赞/评论列表
    public PageResult commentsList(Integer page, Integer pagesize,CommentType type) {
        //获取当前用户id
        Long publishUserId = UserHolder.getUserId();
        //根据发布者id和评论类型查询评论分页列表
       PageResult result = commentApi.findAllCommnets(page,pagesize,publishUserId,type);
        List<Comment> items = (List<Comment>) result.getItems();
        if(items == null){
            return result;
        }
        //从comments中取出评论者id(userId)
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        //查询用户详情
        UserInfo info  = new UserInfo();
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(userIds, info);
        //构建vo
        List<CommentVo> vos = new ArrayList<>();
        for (Comment item : items) {
            UserInfo userInfo = infoMap.get(item.getUserId());
            if(item.getUserId() == publishUserId){
                continue;
            }
            CommentVo vo = CommentVo.init(userInfo, item);
            vos.add(vo);
        }
        //5、构造返回值
        return new PageResult(result.getPage(), result.getPagesize(), result.getCounts(), vos);
    }
}
